#!/usr/bin/env node

const { spawn } = require('child_process')
const path = require('path')

// 启动脚本配置
const apps = [
  { name: 'main-app', port: 8080, path: './main-app' },
  { name: 'master-data-app', port: 8081, path: './apps/master-data-app' },
  { name: 'procurement-app', port: 8082, path: './apps/procurement-app' },
  { name: 'operation-app', port: 8083, path: './apps/operation-app' },
]

console.log('🚀 启动零售ERP微前端开发环境...\n')

// 启动所有应用
apps.forEach(app => {
  console.log(`📦 启动 ${app.name} (端口: ${app.port})`)
  
  const child = spawn('npm', ['run', 'dev'], {
    cwd: path.resolve(__dirname, '..', app.path),
    stdio: 'inherit',
    shell: true
  })

  child.on('error', (error) => {
    console.error(`❌ ${app.name} 启动失败:`, error)
  })

  child.on('close', (code) => {
    if (code !== 0) {
      console.log(`⚠️  ${app.name} 进程退出，退出码: ${code}`)
    }
  })
})

console.log('\n✅ 所有应用启动完成!')
console.log('📱 主应用访问地址: http://localhost:8080')
console.log('🔧 各子应用可独立访问:')
apps.slice(1).forEach(app => {
  console.log(`   - ${app.name}: http://localhost:${app.port}`)
})

// 优雅退出处理
process.on('SIGINT', () => {
  console.log('\n🛑 正在关闭所有应用...')
  process.exit(0)
})

process.on('SIGTERM', () => {
  console.log('\n🛑 正在关闭所有应用...')
  process.exit(0)
})